package com.tinysand.advert.controller;

import com.alibaba.fastjson.JSON;
import com.tinysand.advert.annotation.SkipResponseAdvice;
import com.tinysand.advert.client.SponsorClient;
import com.tinysand.advert.search.Search;
import com.tinysand.advert.search.vo.SearchRequest;
import com.tinysand.advert.search.vo.SearchResponse;
import com.tinysand.advert.support.AdPlan;
import com.tinysand.advert.support.AdPlanGetRequest;
import com.tinysand.advert.support.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 使用 Ribbon & Feign 远程调用广告投放系统服务，由于 Feign 是面向接口形式的调用
 * 使用 Feign 调用服务会更为便捷
 *
 * Created By TINY
 * Create Time 2020/2/27
 **/
@RestController
@Slf4j
public class SearchController {

    private final RestTemplate restTemplate;

    private final SponsorClient sponsorClient;

    private final Search search;

    @Autowired
    public SearchController(RestTemplate restTemplate,
                            SponsorClient sponsorClient,
                            Search search) {
        this.restTemplate = restTemplate;
        this.sponsorClient = sponsorClient;
        this.search = search;
    }

    @PostMapping("/fetchAds")
    public SearchResponse fetchAds(@RequestBody SearchRequest request) {
        return search.fetchAds(request);
    }

    @PostMapping("/ribbon/plan/get")
    @SkipResponseAdvice
    @SuppressWarnings("all")
    public CommonResponse<List<AdPlan>> getAdPlansByRibbon(
            @RequestBody AdPlanGetRequest request) {
        log.info("广告检索模块发起远程调用(Ribbon)，请求对象：（{}）",
                JSON.toJSONString(request));

        return restTemplate.postForEntity(
                "http://eureka-client-advert-sponsor/ad-sponsor/plan/get",
                request, CommonResponse.class).getBody();
    }

    @PostMapping("/plan/get")
    @SkipResponseAdvice
    public CommonResponse<List<AdPlan>> getAdPlansByFeign(
            @RequestBody AdPlanGetRequest request) {
        log.info("广告检索模块发起远程调用(Feign)，请求对象：（{}）",
                JSON.toJSONString(request));

        return sponsorClient.getAdPlanByIds(request);
    }

}
